package com.lysj.bhp.wallet.controller;

import com.lysj.bhp.wallet.base.WalletContent;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.util.BlockChainUtil;
import com.lysj.bhp.recharge.domain.RechargeRecord;
import com.lysj.bhp.user.controller.UserManagerController;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/bitcoin_wallet")
public class BitcoinWalletController extends WalletContent {

    private static Logger logger = LoggerFactory.getLogger(UserManagerController.class);

    @ApiOperation(value = "获取一个比特币钱包", notes = "一个账号只能创建一个钱包")
    @PostMapping("/my_bitcoin_wallet")
    public Resp myBitcoinWallet(String email) throws Exception {
//        return new Resp(Resp.PARAM_ERROR,"系统维护中。。。");
        BitCoinWallet bitCoinWalletQuery = bitcoinWalletRepository.findByUserId(currentUser().getUserId());
        Map<String, String> respMap = new HashMap<>();
        if (bitCoinWalletQuery != null) { // 比特币已经存在，直接返回结果
            return new Resp(Resp.SUCCESS, "您已经有一个比特币钱包了,请不要重复创建",  bitCoinWalletQuery.getLastAddress());
        } else { // 比特币不存在，创建一个新的
            return  blockChainService.createBitcoinWallet(email);
        }
    }


    @ApiOperation(value = "刷新一个比特币地址", notes = "一个账号可以创建多个地址")
    @ApiImplicitParam(name = "lable", value = "地址标签,默认为当前时间字符串", required = false, paramType = "form", dataType = "string")
    @PostMapping("/refresh_bitcoin_address")
    public Resp refreshBitcoinAddress(String lable) throws Exception {
//        return new Resp(Resp.PARAM_ERROR,"系统维护中。。。");
        return blockChainService.refreshBitcoinAddress(lable);
    }


    @ApiOperation(value = "刷新用户比特币钱包", notes = "")
    @PostMapping("/refresh_bitcoin_wallet")
    public Resp refreshBitcoinWallet(Long userId) throws Exception {
        User user = userRepository.findOne(userId);
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "用户不存在");
        }
        logger.info("开始手动刷新比特币钱包，用户Id:" + user.getUserId());
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(userId);
        if (bitCoinWallet == null) {
            return new Resp(Resp.PARAM_ERROR, "该用户没有创建比特币钱包");
        }
        long result = BlockChainUtil.getBitCoinBalance(bitCoinWallet.getGuid(), bitCoinWallet.getPassword());
        System.out.println("接口返回查询到的比特币值为：" + result);
        if (result < 0) { //
            return new Resp(Resp.INNER_ERROR, "查询比特币余额接口有误");
        }
        double realBalance = result * 1.0 / 100000000;
        System.out.println(realBalance);
        if (bitCoinWallet.getBalance().compareTo(BigDecimal.valueOf(realBalance)) != -1) { //查询到的余额小于钱包得真实余额，则更新
            bitCoinWallet.setBalance(BigDecimal.valueOf(realBalance));
        } else {
            bitCoinWallet.setBalance(BigDecimal.valueOf(realBalance));
            BigDecimal increase = BigDecimal.valueOf(realBalance).subtract(bitCoinWallet.getBalance()); // 增加的余额
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(1);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(bitCoinWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecordRepository.save(rechargeRecord);
            userRepository.save(user);
        }
        bitCoinWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        bitcoinWalletRepository.save(bitCoinWallet);
        return new Resp("手动刷新成功");
    }
}
